<template>
  <div class="photographManager">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.photograph_delete" @click="handleDelete">删 除</el-button>
        </template>

        <!-- 隐患照片表格自定义 -->
        <template slot="yhzp" slot-scope="scope">
          <div class="ope_row_div">
            <span v-if="scope.row['yhzp'] === '' || scope.row['bladeFiles'].length === 0">-</span>
            <el-button v-else type="text" @click="handleViewPhoto(scope.row)">查看</el-button>
          </div>
        </template>

        <!-- 隐患照片表单自定义 -->
        <template slot="yhzpForm">
          <div v-if="dialogType !== 'view'">
            <el-button size="small" type="primary" @click="uploadYHZP">上传图片</el-button>
            <span style="margin-left: 10px; color: #606266; font-size: 12px;">只能上传图片，最多选择3张</span>
            <input accept="image/*" ref="yhzpUpload" id="yhzpUpload" style="display: none;" type="file" @change="yhzpUpload" multiple />
          </div>
        </template>

        <!-- 隐患照片内容表单自定义 -->
        <template slot="yhzpContentForm">
          <div class="yhzp_content">
            <el-tag v-for="(item, index) in yhzpFileList" :key="index" type="info" :closable="dialogType !== 'view'" @close="handleRemoveYHZP(index)">
              <img :src="item.response.data.fileUrl" @click="previewYHZP(item)" alt />
            </el-tag>
          </div>
        </template>

        <!-- 审批设置表格自定义 -->
        <template slot="spsz" slot-scope="scope">
          <div>
            <el-button v-if="scope.row['zt'] === 1" type="warning" size="mini" @click="addApprover(scope.row)">添加审批人</el-button>
            <span v-else>-</span>
          </div>
        </template>
        <!-- 情况审批表格自定义 -->
        <template slot="qksp" slot-scope="scope">
          <div>
            <el-button v-if="scope.row['zt'] === 2" type="success" size="mini" @click="handleApproval(scope.row)">审 批</el-button>
            <span v-else>-</span>
          </div>
        </template>

      </avue-crud>

      <!-- 隐患照片弹窗 -->
      <template>
        <div>
          <el-dialog title="隐患照片" append-to-body :visible.sync="localPicBox" :close-on-click-modal="false" :before-close="handleClosePicBox" width="50%">
            <el-carousel indicator-position="outside" trigger="click" :autoplay="false">
              <el-carousel-item v-for="item in imgList" :key="item.id">
                <img :src="item.url" alt />
              </el-carousel-item>
            </el-carousel>
            <div class="view_picture_footer">
              <el-button type="primary" size="small" @click="confirmViewPicture()">确 认</el-button>
            </div>
          </el-dialog>
        </div>
      </template>

      <!-- 弹窗：添加审批人 -->
      <el-dialog
        title="添加审批人"
        append-to-body
        :visible.sync="approverDialog"
        :close-on-click-modal="false"
        :before-close="closeApproverDialog"
        width="60%"
        class="add_violation_dialog"
      >
        <avue-form
          ref="updateForm"
          v-model="updateObj"
          :option="updateOption"
          @submit="confirmApprover"
        >
          <template slot="menuForm">
            <el-button
              size="small"
              icon="el-icon-close"
              @click="closeApproverDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

      <!-- 弹窗：审批情况 -->
      <el-dialog
        title="添加审批情况"
        append-to-body
        :visible.sync="approvalDialog"
        :close-on-click-modal="false"
        :before-close="closeApprovalDialog"
        width="60%"
        class="add_violation_dialog"
      >
        <avue-form
          ref="updateForm1"
          v-model="updateObj1"
          :option="updateOption1"
          @submit="confirmApprovalRelatedParty"
        >
          <template slot="menuForm">
            <el-button
              size="small"
              icon="el-icon-close"
              @click="closeApprovalDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/xjgl/photograph";
  import {removePic, uploadFiles} from "@/api/mmhi/prod_plant";
  import {mapGetters} from "vuex";

  export default {
    props: {
      localPicBox: {default: false},
      localPictures: {default: []}
    },
    data() {
      return {
        form: {},
        query: {},
        imgList: [],
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "名称",
              align: "center",
              maxlength:50,
              prop: "mc",
              rules: [{
                required: true,
                message: "请输入名称",
                trigger: "blur"
              }]
            },
            {
              label: "发现人",
              prop: "fxr",
              type: "select",
              align: "center",
              dicUrl: "/api/emerRectify/rectify/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              rules: [{
                required: true,
                message: "请输入发现人",
                trigger: "blur"
              }]
            },
            {
              label: "发现时间",
              prop: "fxsj",
              align: "center",
              width:"150px",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              rules: [{
                required: true,
                message: "请输入发现时间",
                trigger: "blur"
              }]
            },
            {
              label: "隐患照片",
              prop: "yhzp",
              align: "center",
              slot: true,
              span: 24,
              formslot: true
            },
            {
              label: "",
              prop: "yhzpContent",
              hide: true,
              span: 24,
              formslot: true
            },
            {
              label: "隐患备注",
              prop: "yhbz",
              align: "center",
              type: "textarea",
              maxlength:250,
              span: 24,
              minRows: 6,
              rules: [{
                required: false,
                message: "请输入隐患备注",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "zt",
              search: true,
              type: "select",
              align: "center",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=patrol_photograph",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              display: false,
              dataType:"number"
            },
            {
              label: "审批人",
              prop: "spr",
              type: "select",
              align: "center",
              dicUrl: "/api/emerRectify/rectify/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              addDisplay: false,
              editDisplay: false,
              hide: false
            },
            {
              label: "审批时间",
              prop: "spsj",
              align: "center",
              addDisplay: false,
              editDisplay: false,
              hide: true
            },
            {
              label: "隐患级别",
              prop: "yhjb",
              search: true,
              type: "select",
              align: "center",
              dataType:"number",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=patrol_point_management_xjyhjb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              addDisplay: false,
              editDisplay: false
            },
            {
              label: "审批意见",
              prop: "spyj",
              addDisplay: false,
              editDisplay: false,
              hide: true
            },
            {
              label: "审批设置",
              prop: "spsz",
              align: "center",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: false
            },
            {
              label: "情况审批",
              prop: "qksp",
              align: "center",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: false
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            }
          ]
        },
        data: [],

        // 隐患照片
        yhzpFileList: [],
        dialogType: "",

        // 弹窗：审批设置
        approverDialog: false,
        selectedSettingId:{},
        updateObj:{},
        // 弹窗：审批
        approvalDialog: false,
        approvalPartyId:{},
        updateObj1:{}

      };
    },
    computed: {
      ...mapGetters(["permission"]),

      updateOption() {
        return {
          size: "small",
          submitText: "确 定",
          labelWidth: 110,
          mockBtn: false,
          printBtn: false,
          emptyBtn: false,
          column: [
            {
              label: "审批人",
              prop: "spr",
              span: 12,
              type: "select",
              dicUrl: "/api/emerRectify/rectify/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              rules: [{
                required: true,
                message: "请输入审批人",
                trigger: "blur"
              }]
            }
          ]
        }
      },

      updateOption1() {
        return {
          size: "small",
          submitText: "确 定",
          labelWidth: 110,
          mockBtn: false,
          printBtn: false,
          emptyBtn: false,
          column: [
            {
              label: "隐患级别",
              prop: "yhjb",
              span: 12,
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=patrol_point_management_xjyhjb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请选择隐患级别",
                trigger: "blur"
              }]
            },
            {
              label: "审批时间",
              prop: "spsj",
              span: 12,
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              rules: [{
                required: true,
                message: "请选择审批时间",
                trigger: "change"
              }]
            },
            {
              label: "审批意见",
              prop: "spyj",
              span: 24,
              type: "textarea",
              maxlength: 100,
              rules: [{
                required: true,
                message: "请输入审批意见",
                trigger: "blur"
              }]
            }
          ]
        }
      },

      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.photograph_add, false),
          viewBtn: this.vaildData(this.permission.photograph_view, false),
          delBtn: this.vaildData(this.permission.photograph_delete, false),
          editBtn: this.vaildData(this.permission.photograph_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      //隐患照片id
      picIds() {
        let picIds = [];
        this.selectionList.forEach(ele => {
          picIds.push(ele.yhzp);
        });
        return picIds.join(",");
      }
    },
    methods: {

      // 初始化图片
      initData() {
        this.imgList = [];
        this.localPictures.forEach(item => {
          this.imgList.push({url: item.fileUrl});
        });
      },

      /**
       * 上传隐患照片
       */
      // 上传隐患照片
      yhzpUpload(element) {
        console.log(element);
        if(this.$refs.yhzpUpload.files.length + this.yhzpFileList.length > 3) {
          this.$message.warning("最多上传3张隐患图片!");
          this.$refs.yhzpUpload.value = null;
          return;
        }
        let formData = {};
        let files = this.$refs.yhzpUpload.files;
        formData = new FormData();
        for(let i = 0 ; i < files.length ; i++) {
          formData.append("files", files[i]);
        }
        uploadFiles(formData).then(res => {
          if(!res.data.success) {
            return;
          }
          const resData = res.data.data;
          resData.forEach(item => {
            this.yhzpFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: item
              }
            });
          });
          this.$refs.yhzpUpload.value = null;
        });
      },
      // 点击上传隐患按钮
      uploadYHZP() {
        document.getElementById("yhzpUpload").click();
      },
      // 删除隐患照片
      handleRemoveYHZP(index) {
        this.yhzpFileList.splice(index, 1);
      },

      // 获取隐患照片ids
      formatPictureIds(filelist) {
        const ids = [];
        filelist.forEach(item => {
          ids.push(item.response.data.id);
        });
        return ids.join(",");
      },

      /**
       * 弹窗：图片
       */
      // 查看隐患照片
      handleViewPhoto(row) {
        this.localPictures = row.bladeFiles;
        this.localPicBox = true;
      },

      // 点击图片列表中已上传的隐患图片
      previewYHZP(file) {
        if(file.response && file.response.code === 200 && file.response.data && file.response.data.fileUrl) {
          this.localPictures = [file.response.data];
          this.localPicBox = true;
        }
      },

      // 确认照片
      confirmViewPicture() {
        this.localPictures = [];
        this.localPicBox = false;
        this.$emit('confirmViewPicture');
      },

      // 关闭弹窗
      handleClosePicBox(done) {
        done();
        this.$emit('handleClosePicBox');
      },

      /**
       * 弹窗：添加审批人员
       */

      // 打开人员信息弹窗
      addApprover(row) {
        this.selectedSettingId = row;
        this.updateObj = this.formatUpdateObj(row);
        this.approverDialog = true;
      },

      // 格式化审批设置数据
      formatUpdateObj() {
        var data = {
          spr: "",
        };
        return data;
      },

      // 确定人员
      confirmApprover() {
        this.$refs.updateForm.validate((vaild,done)=>{
          if(vaild){
            this.selectedSettingId.zt = 2;
            this.selectedSettingId.spr = this.updateObj.spr;
            update(this.selectedSettingId).then(res => {
              if(res.data.success) {
                this.closeApproverDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "添加成功!"
                });
              }
            });
            done();
          }
        })
      },

      // 关闭、取消审批设置弹窗
      closeApproverDialog() {
        this.selectedSettingId = {};
        this.approverDialog = false;
      },

      /**
       * 弹窗：情况审批
       */

      // 打开审批弹窗
      handleApproval(row) {
        this.approvalPartyId = row;
        this.updateObj1 = this.formatUpdateObj1(row);
        this.approvalDialog = true;
      },

      // 格式化情况审批数据
      formatUpdateObj1() {
        var data = {
          yhjb: "",
          spsj: "",
          spyj: "",
        };
        return data;
      },

      // 关闭、取消情况审批弹窗
      closeApprovalDialog() {
        this.approvalPartyId = {};
        this.approvalDialog = false;
      },

      // 确认添加审批信息
      confirmApprovalRelatedParty() {
        this.$refs.updateForm1.validate((vaild,done)=>{
          if(vaild){
            this.approvalPartyId.zt = 3 ;
            this.approvalPartyId.yhjb = this.updateObj1.yhjb;
            this.approvalPartyId.spsj = this.updateObj1.spsj;
            this.approvalPartyId.spyj = this.updateObj1.spyj;
            update(this.approvalPartyId).then(res => {
              if(res.data.success) {
                this.closeApprovalDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              }
            });
            done();
          }
        })
      },

      rowSave(row, done, loading) {
        row.zt = 1;
        row.yhzp = this.yhzpFileList.length === 0 ? "" : this.formatPictureIds(this.yhzpFileList);
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

      rowUpdate(row, index, done, loading) {
        row.yhzp = this.yhzpFileList.length === 0 ? "" : this.formatPictureIds(this.yhzpFileList);
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },

      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if (row.yhzp!="") {
            removePic(row.yhzp);
          }
          return remove(row.id);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
      },

      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.picIds.split(",").forEach(picId=>{
            if (picId!=="") {
              removePic(picId);
            }
          });
          return remove(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      },

      beforeOpen(done, type) {
        this.yhzpFileList = [];
        if (["edit", "view"].includes(type)) {
          this.form.bladeFiles.forEach(item => {
            this.yhzpFileList.push({
              name: item.fileName,
              response: {
                code: 200,
                data: item,
                msg: "操作成功",
                success: true
              }
            });
          });
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        this.dialogType = type;
        done();
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },

      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },

      selectionChange(list) {
        this.selectionList = list;
      },

      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },

      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },

      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },

      refreshChange() {
        this.onLoad(this.page, this.query);
      },

      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    },
    watch: {
      localPicBox() {
        if(this.localPicBox === true) {
          this.initData();
        }
      }
    }
  };
</script>

<style lang="scss">
  .photographManager {
    .el-form-item__label {
      width: 95px !important;
    }

    .avue-form__row {
      .el-form-item__content {
        margin-left: 95px !important;
      }
    }
  }

</style>

<style lang="scss" scpoed>
  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 130px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 130px !important;
        }
      }
    }
  }

  .el-dialog__wrapper {
    .el-dialog__body {
      padding: 10px 20px 20px 20px;

      .el-form-item__label {
        width: 72px;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 72px;
        }
      }

      .avue-crud__menu {
        display: none;
      }
    }
  }

  .yhzp_content {
    width: 100%;
    height: 118px;
    line-height: 105px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;

    .el-tag {
      height: 100px;
      line-height: 100px;
      padding: 0px 10px 0px 0px;
      margin-left: 10px;
      margin-top: 10px;

      .el-icon-close {
        top: -84px;
      }
    }

    img {
      width: 98px;
      height: 98px;
      cursor: pointer;
    }
  }

  .ope_row_div {
    .el-button {
      font-size: 12px;
    }
  }

  .el-carousel {
    .el-carousel__container {
      height: 500px;
      text-align: center;

      img {
        height: 100%;
      }
    }
  }

</style>
